package com.haotian.coder.service.Impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;

import com.haotian.coder.exception.ErrorCode;
import com.haotian.coder.exception.ThrowUtils;
import com.haotian.coder.manager.CosManager;
import com.haotian.coder.service.ScreenShotService;
import com.haotian.coder.utils.WebScreenshotUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


@Slf4j
@Service
public class ScreenShotSeriviceImpl implements ScreenShotService {

    @Resource
    private CosManager cosManager;
    @Resource
    private WebScreenshotUtils webScreenshotUtils;


    /**
     * 总方法，供外部调用的接口方法
     *
     * @param webUrl
     * @return
     */
    @Override
    public String generateAndUploadScreenShot(String webUrl) {
        ThrowUtils.throwIf(webUrl == null, ErrorCode.PARAMS_ERROR, "网址不能为空");
        // 截图
        String screenshotPath = WebScreenshotUtils.saveAndCompressScreenshot(webUrl); // 返回的是已压缩的图片
        ThrowUtils.throwIf(screenshotPath == null, ErrorCode.SYSTEM_ERROR, "截图失败");
        try {
            // 上传到COS, 返回访问的url
            String cosUrl = uploadPictureToCos(screenshotPath);
            ThrowUtils.throwIf(cosUrl == null, ErrorCode.SYSTEM_ERROR, "上传图片失败");
            return cosUrl;
        } finally {
            // 清理本地文件
            cleanLocalFile(screenshotPath);
        }
    }


    /**
     * 上传文件对象到 COS
     *
     * @param path
     * @return
     */
    private String uploadPictureToCos(String path) {
        ThrowUtils.throwIf(path == null, ErrorCode.PARAMS_ERROR, "图片路径不能为空");

        final String SUFFIX = "_compress.jpg";

        File file = new File(path);
        if (!file.exists()) {
            throw new RuntimeException("图片不存在");
        }

        // 生成cos对象键
        String fileName = RandomUtil.randomString(6) + SUFFIX;
        String cosKey = generateUploadKey(fileName);
        return cosManager.upLoadFile(cosKey, file);
    }

    /**
     * 清理本地文件
     *
     * @param path
     */
    private void cleanLocalFile(String path) {
        File file = new File(path);
        if (file.exists()) {
            FileUtil.del(file);
            log.info("本地截图文件已删除，路径为->{}", path);
        }
    }

    /**
     * 生成截图的对象存储键
     * 格式：/screenshots/2025/07/31/filename.jpg
     */
    private String generateUploadKey(String filename) {

        String dateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));

        return String.format("/screenshots/%s/%s.jpg", dateTime, filename);
    }


}
